//
//  HJAlertController.m
//  Community
//
//  Created by xtjun on 2023/7/4.
//

#import "HJAlertController.h"
#import "HJButton.h"

@interface HJAlertAction ()


@end

@implementation HJAlertAction

- (instancetype)init {
    if (self = [super init]) {
        _titleColor = UIColor.tj_101320Color;
    }
    return self;
}

@end


@interface HJAlertController ()

@property (nonatomic, copy) NSString *message;
@property (nonatomic, strong) NSMutableArray <HJAlertAction *> *actions;
@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) HJAlertAction *cancelAction;
@property (nonatomic, strong) HJAlertAction *confirmAction;
@property (nonatomic, weak) UILabel *messageLabel;
@property (nonatomic, weak) UILabel *titleLabel;
@property (nonatomic, weak) UIView *lastView;
@property (nonatomic, strong) UIFont *buttonFont;
@property (nonatomic, strong) UIFont *messageFont;

@end

 

@implementation HJAlertController

 
+ (void)alertInController:(UIViewController *)controller title:(nullable NSString *)title message:(nullable NSString *)message left:(nullable void (^)(HJAlertAction *action))left right:(nullable void (^)(HJAlertAction *action))right {
    
    if (HJTools.tool.alertController) return ;

    if (title.length <= 0 && message.length <= 0) return ;

    HJAlertController *alertController = [[HJAlertController alloc] init];
    alertController.title = title;
    alertController.message = message;
    if (left) {
        HJAlertAction *leftAction = [[HJAlertAction alloc] init];
        [alertController.actions addObject:leftAction];
        left(leftAction);
    }
    
    if (right) {
        HJAlertAction *rightAction = [[HJAlertAction alloc] init];
        [alertController.actions addObject:rightAction];
        right(rightAction);
    }
    HJTools.tool.alertController = alertController;
    [controller presentViewController:alertController animated:NO completion:nil];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
        self.messageColor = UIColor.tj_474D5EColor;
        self.titleColor = UIColorMake(0x011126);
        self.messageFont = UIFontMake(15);
        self.buttonFont = UIFontMake(16);
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];

    UIView *contentView = [UIView addToView:self.view];
    contentView.addCornerRadius(20);
    contentView.backgroundColor = UIColor.whiteColor;
    _contentView = contentView;
    [contentView clipsToBounds];

    CGFloat contentWidth = 280;
    CGFloat topMargin = 20;
    CGFloat _leftRightMargin = 20;
    
    UIView *titleView = [UIView addToView:contentView];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:contentView font:UIFontBoldMake(17) color:self.titleColor title:self.title textAlignment:NSTextAlignmentCenter];
    titleLabel.numberOfLines = 0;

    titleLabel.attributedText = [self.title titleMargin:2 alignment:NSTextAlignmentCenter];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(topMargin);
        make.centerX.offset(0);
        make.width.mas_lessThanOrEqualTo(contentWidth - _leftRightMargin * 2);
    }];
    
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.offset(0);
        make.bottom.equalTo(titleLabel.mas_bottom);
    }];
    
    if (isEmptyString(self.title)) {
        [titleView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.right.left.offset(0);
            make.height.offset(10);
            make.bottom.equalTo(titleLabel.mas_bottom);
        }];
        self.messageFont = UIFontMake(16);
    } else {
        self.messageFont = UIFontMake(14);
    }
    _lastView = nil;
    
    UILabel *messageLabel = [UILabel lableWithSuperView:contentView font:_messageFont color:_messageColor title:_message textAlignment:NSTextAlignmentCenter];
    messageLabel.numberOfLines = 0;
    messageLabel.attributedText = [_message titleMargin:3 alignment:NSTextAlignmentCenter];
    [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleView.mas_bottom).offset(8);
        make.centerX.offset(0);
        make.width.offset(contentWidth - _leftRightMargin * 2);
        make.height.mas_greaterThanOrEqualTo(40);
    }];
    
    _lastView = messageLabel;
    _messageLabel = messageLabel;
    _titleLabel = titleLabel;
    
    BOOL isOnlyLine = [_message getStringSizeWithWidth:contentWidth - _leftRightMargin * 2 font:_messageFont].height < 25;
    
    UIView *bottomView = [UIView addToView:contentView];
    bottomView.backgroundColor = contentView.backgroundColor;
    [bottomView clipsToBounds];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(_lastView.mas_bottom).offset(isOnlyLine ? 15 : 18);
        make.left.right.inset(15);
        make.height.offset(44);
    }];
 
    if (self.actions.count == 1) {
        
        HJAlertAction *action = self.actions.firstObject;
        
        HJButton *button = [HJButton addToView:bottomView];
        [button setTitle:action.title forState:UIControlStateNormal];
        [button setTitleColor:action.titleColor forState:UIControlStateNormal];
        button.titleLabel.font = self.buttonFont;
        button.backgroundColor = action.backgroundColor;
        button.anyObject = action;
        button.addCornerRadius(10);
        [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.offset(0);
            make.center.offset(0);
            make.width.mas_equalTo(bottomView).multipliedBy(0.5);
        }];
        
    } else {
 
        [self.actions enumerateObjectsUsingBlock:^(HJAlertAction *  _Nonnull action, NSUInteger idx, BOOL * _Nonnull stop) {
            
            HJButton *button = [HJButton addToView:bottomView];
            button.anyObject = action;
            [button setTitle:action.title forState:UIControlStateNormal];
            [button setTitleColor:action.titleColor forState:UIControlStateNormal];
            button.titleLabel.font = self.buttonFont;
            button.backgroundColor = action.backgroundColor;
            [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
            button.addCornerRadius(10);

            if (idx == 0) {
                [button mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.inset(0);
                    make.top.offset(0);
                    make.right.equalTo(contentView.mas_centerX).inset(5);
                    make.bottom.offset(0);
                }];
            } else {
                [button mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.inset(0);
                    make.top.offset(0);
                    make.left.equalTo(contentView.mas_centerX).inset(5);
                    make.bottom.offset(0);
                }];
            }
        }];
    }
    
    _lastView = bottomView;
    
    [self.view layoutIfNeeded];
    
    CGFloat contentHeight = CGRectGetMaxY(_lastView.frame) + 15;
    contentView.frame = CGRectMake((KScreenWidth - contentWidth) * 0.5, (KScreenHeight - contentHeight) * 0.5 - 30, contentWidth, contentHeight);
    
}

- (NSMutableArray<HJAlertAction *> *)actions {
    if (!_actions) {
        _actions = [NSMutableArray array];
    }
    return _actions;
}
- (void)didClickButton:(HJButton *)button {
 
    [UIView animateWithDuration:0.15 animations:^{
        self.view.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
        self.contentView.alpha = 0;
    } completion:^(BOOL finished) {
        HJTools.tool.alertController = nil;
        [self dismissViewControllerAnimated:NO completion:^{
            HJAlertAction *action = button.anyObject;
            if (action && action.handler) {
                action.handler();
            }
        }];
   
    }];
}
 

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.contentView.layer.transform = CATransform3DMakeScale(0.7, 0.7, 0.7);
    self.contentView.alpha = 0.7;
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.70 initialSpringVelocity:0.8 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.contentView.alpha = 1;
        self.contentView.layer.transform = CATransform3DMakeScale(1, 1, 1);
        self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];
    } completion:^(BOOL finished) {
        
    }];
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}
 
@end




//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"标题" message:@"消息" preferredStyle:UIAlertControllerStyleAlert];
//
//    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        // 处理确定按钮点击事件
//    }];
//
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        // 处理取消按钮点击事件
//    }];
//
//    [alertController addAction:okAction];
//    [alertController addAction:cancelAction];
//
//    // 获取对按钮的引用
//    UIAlertAction *okButton = [alertController.actions objectAtIndex:0];
//    UIAlertAction *cancelButton = [alertController.actions objectAtIndex:1];
//
//    [okButton setValue:[UIColor greenColor] forKey:@"_titleTextColor"];
//    [cancelButton setValue:[UIColor orangeColor] forKey:@"titleTextColor"];
//
//
//    NSString * messageStr = @"真的要退出此账号么?";
//    //改变message的大小和颜色
//    NSMutableAttributedString *messageAtt = [[NSMutableAttributedString alloc] initWithString:messageStr];
//    [messageAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.f] range:NSMakeRange(0, messageStr.length)];
//    [messageAtt addAttribute:NSForegroundColorAttributeName value:[UIColor cyanColor] range:NSMakeRange(0, messageStr.length)];
//    //KVC:改变字体(富文本)
//    [alertController setValue:messageAtt forKey:@"attributedMessage"];
//
//    NSString *titleStr = @"4y69461946";
//    NSMutableAttributedString *titleAtt = [[NSMutableAttributedString alloc] initWithString:titleStr];
//    [titleAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16.f] range:NSMakeRange(0, titleStr.length)];
//    [titleAtt addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, titleStr.length)];
//    //KVC:改变字体(富文本)
//    [alertController setValue:titleAtt forKey:@"attributedTitle"];
//
//
//    // 显示 UIAlertController
//    [self presentViewController:alertController animated:YES completion:nil];
